package com.zxmr.component;

import java.util.UUID;
import java.util.concurrent.ExecutorService;

import com.zxmr.CommonInit;
import com.zxmr.action.QueueWithExchangeReceiver;
import com.zxmr.action.QueueWithoutExchangeReceiver;
import com.zxmr.navigate.RequestDispatch;
import com.zxmr.navigate.XMLConfigurationLoader;

public class SimpleServerStarter {

	
	String queue = null; 
	QueueWithExchangeReceiver requestReceiver = null;
	QueueWithoutExchangeReceiver responseReceiver = null;
	

	public  void start(String queue,ExecutorService executor) {

		this.queue = queue;
		initDB();

		startRequestReceiverQueue(executor);
		startResponseReceiverQueue(executor);

		startRequestDispatch();
		

	}
	private void initDB()
	{
		CommonInit.initCommonSqlMapper(SystemConstant.getBasedir()+"common-part-db-config.xml");
		SystemConstant.initDB();
		
	}
	private void startRequestDispatch()
	{
		String url = "dispatch.xml";
		
		String propsPath =  SystemConstant.getBasedir()+url;
		
		XMLConfigurationLoader loader = new XMLConfigurationLoader();
		loader.load(propsPath);
		
		RequestDispatch.init(loader);
	}

	/**
	 * the queue used to receive request when the component act as a server
	 * @param es
	 */
	private void startRequestReceiverQueue(ExecutorService es)
	{
		requestReceiver = new QueueWithExchangeReceiver(es,queue);

		Thread requestReceiverThread = new Thread(requestReceiver);
		requestReceiverThread.setName("requestReceiverThread");
		requestReceiverThread.start();
	}
	/**
	 * the queue used to receive response when the component act as a client
	 * @param es
	 */
	private void startResponseReceiverQueue(ExecutorService es)
	{
		String responseQueue = getUUID();
		responseReceiver = new QueueWithoutExchangeReceiver(es,responseQueue);

		
		Thread responseReceiverThread = new Thread(responseReceiver);
		responseReceiverThread.setName("responseReceiverThread");
		responseReceiverThread.start();
	}
	/**
	 * generate unique ID for response queue
	 * @return
	 */
	private String getUUID()
	{
		return UUID.randomUUID().toString();
	}
	
}
